package com.czkevin.wusan.listeners;

import com.czkevin.cif.CIFItemInstance;
import com.czkevin.cif.CustomItemFramework;
import com.czkevin.wusan.items.BaseWuSanItem;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.*;
import org.bukkit.inventory.ItemStack;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;

import java.util.HashSet;
import java.util.Set;
import java.util.UUID;

public class ItemSwitchListener implements Listener {

    @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
    public void onItemSwitch(PlayerItemHeldEvent event) {
        if (checkWuSan(event.getPlayer().getInventory().getItem(event.getPreviousSlot()))) {
            removeEffects(event.getPlayer());
        }
        if (checkWuSan(event.getPlayer().getInventory().getItem(event.getNewSlot()))) {
            applyEffects(event.getPlayer());
        }
    }

    @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
    public void onSwitchHand(PlayerSwapHandItemsEvent event) {
        if(checkWuSan(event.getMainHandItem()) || checkWuSan(event.getOffHandItem())) {
            applyEffects(event.getPlayer());
        }
    }

    @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
    public void onJoin(PlayerJoinEvent event) {
        if(checkWuSan(event.getPlayer().getInventory().getItemInMainHand()) || checkWuSan(event.getPlayer().getInventory().getItemInOffHand())) {
            applyEffects(event.getPlayer());
        }
    }

    @EventHandler
    public void onQuit(PlayerQuitEvent event) {
        removeEffects(event.getPlayer());
    }

    public static boolean checkWuSan(ItemStack item) {
        if(item == null || item.getType() == Material.AIR) return false;
        CIFItemInstance instance = CustomItemFramework.getCIFDataFromItem(item);
        if(instance == null || instance.type == null || !BaseWuSanItem.class.isAssignableFrom(instance.type.getClass())) return false;
        return true;
    }


    public static final Set<UUID> affectedPlayers = new HashSet<>();

    public static void applyEffects(Player player) {
        affectedPlayers.add(player.getUniqueId());
        player.addPotionEffect(new PotionEffect(
            PotionEffectType.CONFUSION,
            999999,
            2,
            false, false, true
        ));
        player.addPotionEffect(new PotionEffect(
            PotionEffectType.WITHER,
            999999,
            2,
            false,
            true,
            true
        ));
    }

    public static void removeEffects(Player player) {
        if(affectedPlayers.remove(player.getUniqueId())) {
            player.removePotionEffect(PotionEffectType.CONFUSION);
            player.removePotionEffect(PotionEffectType.WITHER);
        }
    }

}
